package com.yungu.swift.admin.utils;


import com.yungu.swift.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 将关键数据进行加密
 */
public class RandomCipherUtils {

    private static final String MESSAGE_KEY = "AESCipher1234567";
    private static final String WRAP_KEY = "YYcx1289qazRan@!";
    private static List<Pattern> patterns = null;

    /**
     * 9sQqwKeE+WOdSChiA+A/lKYcmCjQpZBT0By7YJObG4IFXMT/MmzxswtGfDoQqjxg&codeType=1&sendType=1&noncestr=
     * 加密
     * ASE(8（随机8位）+ 数据(ASE) + 8（随机8位）)
     *
     * @param value
     * @return
     */
    public static String randomEncrypt(String value) {
        if (StringUtils.isEmpty(value)) {
            return "";
        }
        return AESCipher.encryptAES(randomString(8) + AESCipher.encryptAES(value, RandomCipherUtils
                .MESSAGE_KEY) + randomString(8), RandomCipherUtils.WRAP_KEY).replaceAll("\\+",
                "-").replaceAll("/", "_").replaceAll("=", "");
    }

    /**
     * 解密
     *
     * @param value
     * @return
     */
    public static String randomDecrypt(String value) {
        if (StringUtils.isEmpty(value)) {
            return "";
        }
        if (value.length() == 4 || value.length() == 11 || value.length() == 18) {
            return value;
        }
        //BASE64编码：1变2、2变3，对4取余，最多补两个等号  -- by yun
        int mod4 = value.length() % 4;
        if (mod4 > 0) {
            value = value + "====".substring(mod4);
        }
        value = AESCipher.decryptAES(value.replaceAll("_", "/").replaceAll("-", "+"), WRAP_KEY);
        if (StringUtils.isEmpty(value)) {
            return "";
        }
        value = AESCipher.decryptAES(value.substring(8, value.length() - 8), RandomCipherUtils.MESSAGE_KEY);
        //因为部分字段单独处理加密 在此增加xss过滤
        value = stripXss(value);
        return value;
    }

    /**
     * 产生一个随机的字符串
     */
    private static String randomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            //62顺位
            int num = random.nextInt(62);
            sb.append(str.charAt(num));
        }
        return sb.toString();
    }

    private static List<Object[]> getXssPatternList() {
        List<Object[]> list = new ArrayList<Object[]>();
        list.add(new Object[]{"<(no)?script[^>]*>.*?</(no)?script>", Pattern.CASE_INSENSITIVE});
        list.add(new Object[]{"eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        list.add(new Object[]{"expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        list.add(new Object[]{"(javascript:|vbscript:|view-source:|script:)*", Pattern.CASE_INSENSITIVE});
        list.add(new Object[]{"<(\"[^\"]*\"|\'[^\']*\'|[^\'\">])*>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        list.add(new Object[]{"(window\\.location|window\\.|\\.location|document\\.cookie|document\\.|alert\\(.*?\\)|window\\.open\\()*", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        list.add(new Object[]{"<+\\s*\\w*\\s*(oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror=|onerroupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmousout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onabort|onactivate|onafterprint|onafterupdate|onbefore|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload)+\\s*=+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        return list;
    }

    private static List<Pattern> getPatterns() {
        if (patterns == null) {
            List<Pattern> list = new ArrayList<Pattern>();
            String regex;
            Integer flag;
            int arrLength;
            for (Object[] arr : getXssPatternList()) {
                arrLength = arr.length;
                for (int i = 0; i < arrLength; i++) {
                    regex = (String) arr[0];
                    flag = (Integer) arr[1];
                    list.add(Pattern.compile(regex, flag));
                }
            }
            patterns = list;
        }
        return patterns;
    }

    static String stripXss(String value) {
        if (com.yungu.swift.utils.StringUtils.isNotEmpty(value)) {
            Matcher matcher;
            for (Pattern pattern : getPatterns()) {
                matcher = pattern.matcher(value);
                // 匹配
                if (matcher.find()) {
                    // 删除相关字符串
                    value = matcher.replaceAll("");
                }
            }
        }
        value = value.replaceAll("<", "").replaceAll(">", "");
        return value;
    }

}
